<template>
  <el-menu-item
    v-if="
      hasOneShowingChild(item.children, item) &&
      (!onlyOneChild.children || onlyOneChild.noShowingChildren) &&
      !item.alwaysShow
    "
    :index="item.path"
    @click="clickHandle(item)"
    :class="{ 'submenu-title-noDropdown': !isNest }"
  >
    <MenuItem :icon="item.meta.icon" :title="onlyOneChild.meta.title" />
  </el-menu-item>
  <el-submenu v-else ref="subMenu" :index="item.path" popper-append-to-body>
    <template slot="title">
      <MenuItem :icon="item.meta.icon" :title="item.meta.title" />
    </template>
    <sidebar-item
      v-for="(child, index) in item.children"
      :key="child.path + index"
      :is-nest="true"
      :item="child"
      class="nest-menu"
    />
  </el-submenu>
</template>

<script>
import MenuItem from './MenuItem.vue'
export default {
  name: 'SidebarItem',
  props: {
    // route object
    item: {
      type: Object,
      required: true
    },
    isNest: {
      type: Boolean,
      default: false
    }
  },
  components: {
    MenuItem
  },
  data() {
    this.onlyOneChild = null
    return {}
  },
  methods: {
    // 单击选择
    clickHandle(item) {
      // 外部链接
      if (item.meta.isLink) {
        window.open(item.meta.isLink, '_blank')
        return
      }
      // 普通路由跳转
      if (!item.children) {
        this.$router.push({ path: item.path })
      }
    },
    hasOneShowingChild(children = [], parent) {
      const showingChildren = children.filter((item) => {
        if (item.hidden) {
          return false
        } else {
          this.onlyOneChild = item
          return true
        }
      })
      if (showingChildren.length === 0) {
        this.onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return true
      }

      return false
    }
  }
}
</script>

<style lang="scss"></style>
